<?php
namespace app\models;

use Yii;
use app\models\Basic;

class Member extends Basic
{
    public $passwordConfirm;
    
    public static function tableName()
    {
        return '{{%pj8_member}}';
    }

    public function rules()
    {
        return [
            ['loginname', 'required', 'message' => 'loginname不能为空', 'on' => 'add'],
            ['loginname', 'string', 'message' => 'loginname必须是字符串',
                         'min' => 3, 'tooShort' => 'loginname最短3位',
                         'max' => 32, 'tooLong' => 'loginname最长32位'],
            ['loginname', 'validateLoginnameRepeat', 'on' => ['add', 'mod']],
            ['phone', 'validatePhoneRepeat', 'on' => ['add', 'mod']],
            ['phone', 'validatePhone', 'on' => ['forget']],
            ['phone', 'string', 'message' => 'phone必须是字符串',
                      'min' => 11, 'tooShort' => 'phone最短11位',
                      'max' => 11, 'tooLong' => 'phone最长11位'],
            ['email', 'string', 'message' => 'email必须是字符串',
                      'min' => 3, 'tooShort' => 'email最短3位',
                      'max' => 32, 'tooLong' => 'email最长32位'],
            ['password', 'required', 'message' => 'password不能为空', 'on' => ['add', 'login', 'modPassword']],
            ['password', 'string', 'message' => 'password必须是字符串'],
            ['password', 'validatePass', 'on' => 'login'],
            ['passwordConfirm', 'required', 'message' => '确认密码不能为空', 'on' => ['add', 'modPassword']],
            ['passwordConfirm', 'compare', 'compareAttribute' => 'password', 'message' => '两次密码不一致', 'on' => ['add', 'modPassword', 'forget']],
            ['account', 'integer', 'message' => 'account必须为数字，或数字字符串', 
                         'min'=>1, 'tooSmall' => 'account最小存储1'],
            ['nickname', 'string', 'message' => 'nickname必须是字符串', 
                                   'max' => 18, 'tooLong' => 'nickname最长18位'],
            ['sex', 'in', 'range' => ['0', '1', '2'],  'message' => '性别格式不正确'],
            ['signature', 'string', 'message' => 'signature必须是字符串', 
                                   'max' => 512, 'tooLong' => 'signature最长512位'],
            ['headimgurl', 'required', 'message' => 'headimgurl不能为空', 'on' => 'modHeadimgurl'],
            ['headimgurl', 'string', 'message' => 'headimgurl必须是字符串', 
                                   'max' => 512, 'tooLong' => 'headimgurl最长512位'],
            ['wechat_openid', 'required', 'message' => 'wechat_openid不能为空', 'on' => 'modwechat_openid'],
            ['wechat_openid', 'string', 'message' => 'wechat_openid必须是字符串', 
                                   'max' => 512, 'tooLong' => 'wechat_openid最长512位'],
            ['province', 'string', 'message' => 'province必须是字符串', 
                         'max' => 16, 'tooLong' => 'province最长16位'],
            ['city', 'string', 'message' => 'city必须是字符串', 
                     'max' => 16, 'tooLong' => 'city最长16位'],
            ['district', 'string', 'message' => 'district必须是字符串', 
                         'max' => 16, 'tooLong' => 'district最长16位'],
            ['lastloginip', 'string', 'message' => 'lastloginip必须是字符串', 
                            'max' => 64, 'tooLong' => 'lastloginip最长64位'], 
            ['lastlogin_time', 'default', 'value' => '1000-01-01 00:00:00'],
            ['lastlogin_time', 'date', 'format'=>'yyyy-MM-dd HH:mm:ss', 'message' => 'lastlogin_time非yyyy-MM-dd HH:mm:ss格式'],
            ['state', 'integer', 'message' => 'state必须为数字，或数字字符串'],
            ['state', 'in', 'range' => array(1, 2), 'message' => 'state值必须在1,2中选择'],
            ['logintimes', 'integer', 'message' => 'logintimes必须为数字，或数字字符串', 
                           'min'=>0, 'tooSmall' => 'logintimes最小存储0', 
                           'max'=>4294967295, 'tooBig' => 'logintimes最大存储4294967295'],
            ['regip', 'string', 'message' => 'regip必须是字符串', 
                            'max' => 64, 'tooLong' => 'regip最长64位'], 
            ['regclient', 'string', 'message' => 'regclient必须是字符串', 
                          'max' => 512, 'tooLong' => 'regclient最长512位'],
            ['regfrom', 'integer', 'message' => 'regfrom必须为数字，或数字字符串'],
            ['regfrom', 'in', 'range' => array(1, 2, 3), 'message' => 'regfrom值必须在1,2,3中选择'],
            ['add_time', 'default', 'value' => '1000-01-01 00:00:00'],
            ['add_time', 'date', 'format'=>'yyyy-MM-dd HH:mm:ss', 'message' => 'add_time非yyyy-MM-dd HH:mm:ss格式'],
        ];
    }

    /*rules 验证登录信息是否吻合*/
    public function validatePass()
    {
        if(!$this->hasErrors()){
            if(isset($this->loginname)){
                $data = self::find()
                ->where('loginname = :uname and password = :pass', [':uname' => $this->loginname, ':pass' => md5($this->password)])->one();
            }
            if(isset($this->phone)){
                $data = self::find()
                ->where('phone = :phone and password = :pass', [':phone' => $this->phone, ':pass' => md5($this->password)])->one();
            }
            // P($data);
            // P(md5(md5($this->password).$this->comid));
            if(is_null($data)){
                $this->addError('passwordError', '账号或密码错误');
            }else if($data->state == 1){
                $this->addError('stateError', '该账户已经被锁定');
            }
        }
    }

    /*rules 验证会员名是否存在*/
    public function validateLoginnameRepeat()
    {
        if(!$this->hasErrors() and isset($this->loginname)){
            $data = self::find()
                    ->where('loginname = :uname', [':uname' => $this->loginname])
                    ->one();
            if(!is_null($data)){
                $this->addError('repeatLoginname', '该会员名已经存在');
            }
        }
    }

    /*rules 验证手机是否存在*/
    public function validatePhoneRepeat()
    {
        if(!$this->hasErrors() and isset($this->phone)){
            $data = self::find()
                    ->where('phone = :phone', [':phone' => $this->phone])
                    ->one();
            if(!is_null($data)){
                $this->addError('repeatPhone', '该手机号已经存在');
            }
        }
    }

    /*rules 通过手机号码 查出会员信息,*/
    public function validatePhone()
    {
        if(!$this->hasErrors()){
            $data = self::find()
                    ->where('phone = :phone', [':phone' => $this->phone])
                    ->one();
            if(is_null($data)){
                $this->addError('phone', '该用户不存在');
            }
        }
    }

    /*登录*/
    public function login($data)
    {
        // P($data);
        $this->scenario = 'login';
        if($this->load($data) and $this->validate()){//验证成功
            /*更新最后登录时间 和 登录次数*/
            if(isset($this->loginname)){
                $this->updateAll(['lastloginip' => Yii::$app->request->userIP, 'lastlogin_time' => date('Y-m-d H:i:s', time())], 'loginname = :uname', [':uname' => $this->loginname]);
                $this->updateAllCounters(['logintimes' => 1], 'loginname = :uname', [':uname' => $this->loginname]);
                /*取出登录了信息*/
                $info = $this::find()
                            ->where('loginname = :uname and password = :pass', [':uname' => $this->loginname, ':pass' => md5($this->password)])->asArray()->one();
            }
            if(isset($this->phone)){
                $this->updateAll(['lastloginip' => Yii::$app->request->userIP, 'lastlogin_time' => date('Y-m-d H:i:s', time())], 'phone = :phone', [':phone' => $this->phone]);
                $this->updateAllCounters(['logintimes' => 1], 'phone = :phone', [':phone' => $this->phone]);
                /*取出登录了信息*/
                $info = $this::find()
                            ->where('phone = :phone and password = :pass', [':phone' => $this->phone, ':pass' => md5($this->password)])->asArray()->one();
            }
            // P($info);
            /*登录信息存入缓存*/
            // $loginInfo = array(
            //     'userInfo' => $info,
            // );
            // Yii::$app->session->set('loginInfo', (object)$loginInfo);
            return $info;
        }
        return false;
    }

    /*忘记密码 通过手机号找回*/
    public function forgetByPhone($data)
    {
        // P($data);
        $this->scenario = 'forget';
        if($this->load($data) and $this->validate()){//验证成功
            $this->password = md5($data['Member']['password']);
            // P($this->password);
            $this->updateAll(['password' => $this->password], 'phone = :phone', [':phone' => $this->phone]);
            return true;
        }
        return false;
    }


    /*添加会员*/
    public function addMember($data)
    {
        // $this->scenario = 'add';
        if(isset($_SERVER['HTTP_USER_AGENT'])){
            $data['Member']['regclient'] = $_SERVER['HTTP_USER_AGENT'];
        }
        $data['Member']['add_time'] = date('Y-m-d H:i:s', time());

        // P($data);
        if($this->load($data) and $this->validate()){
            $this->loginname = $this->createLoginname();
            $this->password = md5($this->loginname);
            if($this->save(false)){
                // return $this->comid;
                $id = $this->getPrimaryKey();
                return $id;
            }
        }
        return false;
    }

    /*
    修改会员
    $data   修改的数据
    $id     主键
    */
    public function modifyMember($data, $id)
    {
        if(isset($data['Member']['password'])){//只修改密码
            $this->scenario = 'modPassword';
        }else{
            $this->scenario = 'mod';
        }
        $member = Member::find()->where('member_id = :id', [':id' => $id])->one();
        // P($data);
        if(!is_null($member)){
            if($this->load($data) and $this->validate()){
                if(isset($this->loginname)){
                    $member->loginname = $this->loginname;
                }
                if(isset($this->phone)){
                    $member->phone = $this->phone;
                }
                if(isset($this->email)){
                    $member->email = $this->email;
                }
                if(isset($this->password)){
                    $this->password = md5($this->password);
                    $member->password = $this->password;
                }
                if(isset($this->nickname)){
                    $member->nickname = $this->nickname;
                }
                if(isset($this->sex)){
                    $member->sex = $this->sex;
                }
                if(isset($this->signature)){
                    $member->signature = $this->signature;
                }
                if(isset($this->headimgurl)){
                    $member->headimgurl = $this->headimgurl;
                }
                if(isset($this->province)){
                    $member->province = $this->province;
                }
                if(isset($this->city)){
                    $member->city = $this->city;
                }
                if(isset($this->district)){
                    $member->district = $this->district;
                }
                if(isset($this->state)){
                    $member->state = $this->state;
                }
                if($member->save(false)){
                    return true;
                }
            }
        };
        return false;
    }

    /*产生一个唯一的用户名*/
    private function createLoginname() {
        $loginname = date('Ym', time()).mt_rand(1000, 9999).date('d', time());
        $member = self::find()->where('loginname = :name', [':name' => $loginname])->one();
        return $member?$this->createLoginname():$loginname;  //如果重复则重新生成 
    }
    
}